package cn.juc;

import javafx.scene.control.Slider;
import lombok.extern.slf4j.Slf4j;

/**
 * 保护性暂停 升级版本
 */
@Slf4j
public class GuardObject {
    private Object response;
    private synchronized Object get(long timeout){
        log.debug("判断是否唤醒");
        long begin=System.currentTimeMillis();
        long pass_time=0;
        while (this.response==null){
            //如果超时
            if (pass_time>=timeout){
                log.info("等待超时");
                //强制返回
                //同时锁也会得到释放
                break;
            }
            try {
                this.wait(timeout-pass_time);//没有回应就等待
                log.info("唤醒成功");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pass_time=System.currentTimeMillis()-begin;
        }
        return this.response;
    }
    private  synchronized void set(Object o){
        this.response=o;
        log.info("开始回应");
        this.notifyAll();//防止假唤醒
    }

    public static void main(String[] args) throws InterruptedException {
        GuardObject guardObject=new GuardObject();
       new Thread(()->{
           log.info("等待");
           Object o = guardObject.get(1000);
           log.info("结果"+o);
       },"t1").start();
      /* new Thread(()->{
           log.debug("执行任务");
           try {
               Thread.sleep(5000);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           guardObject.set(new Object());
       },"t2").start();*/
    }

}
